package com.hanbang.taitaigou.ui.activity.taitaigou;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.CommodityClassifyData;
import com.hanbang.taitaigou.model.DbGwcData;
import com.hanbang.taitaigou.model.GoodListData;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.MainBaseActivity;
import com.hanbang.taitaigou.ui.activity.home.AddAddressActivity;
import com.hanbang.taitaigou.ui.activity.home.MainActivity;
import com.hanbang.taitaigou.ui.activity.home.SearchActivity;
import com.hanbang.taitaigou.ui.widget.NumberSelectView;
import com.hanbang.taitaigou.ui.widget.autoloadding.ListViewForAutoLoad;
import com.hanbang.taitaigou.ui.widget.autoloadding.OnLoaddingListener;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.http.PagingHelp;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class TaiTaiGouActivity extends MainBaseActivity {

    //titlebar
    private ImageView top_bar_right_iv, top_bar_loc;
    public TextView top_bar_title;
    public static String sstr = "";
    private int sjID = -1;

    public MainActivity mainActivity;


    /**
     * 左侧菜单栏
     */
    private ListView listViewKey;
    private List<CommodityClassifyData> list = new ArrayList<>();
    private ListViewKeyAdapter listViewKeyAdapter;

    /**
     * 右侧结果栏
     */
    private ListViewForAutoLoad listViewValue;
    private ListViewValueAdapter customAdapter;
    private List<GoodListData> data = new ArrayList<>();
    private SwipeRefreshLayout valueSwipeRefreshLayout;

    private LinearLayout ll_yc;
    private LinearLayout ll_xs;
    private TextView tv_zcsx;

    private PagingHelp pageHelp;
    private static int selectIndex = 0;

    private ImageView logo;
    private TextView tv_logo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.more_good);
        initView();
        setOnClickListener();
        intentJX(getIntent(), true);
        getHttpClassList();
        shuaxin();


        IntentFilter intentFilter = new IntentFilter(GwcDbUtil.GWC_CHANG_CLEAR);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_ADD);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_SUB);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG);
        intentFilter.addAction(GwcDbUtil.DELETE_DB);
        registerReceiver(broadcastReceiver, intentFilter);


        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction("setTranslate");
        intentFilter1.addAction("sengAddress");
        registerReceiver(broadcastReceiver2, intentFilter1);

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        intentJX(intent, false);
    }

    public void startXQ(Context context, String number, String dept_id, String id, String title) {
        Intent intent = new Intent(context, ProductDetailsActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("dept_id", dept_id);
        intent.putExtra("title", title);
        intent.putExtra("number", number);
//        context.startActivity(intent);
        startActivity(intent);
    }

    public static void startUi(Context context, int dept_id) {

        if (dept_id < 0) {
            return;
        }
        Intent intent = new Intent(context, TaiTaiGouActivity.class);
        intent.putExtra("dept_id", dept_id);
        LogUtils.e("dept_id", dept_id + "");
//        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        context.startActivity(intent);
    }

    /**
     * 意图解析
     */
    private void intentJX(Intent intent, boolean isOnCreate) {

//        selectIndex = 0;
        if (intent != null) {
            int dept_id = intent.getIntExtra("dept_id", -1);
            LogUtils.e("intentJX", dept_id + "");
            if (dept_id != -1) {
                int temp = getDeptIdToPosition(dept_id);
                if (temp != 0) {
                    selectIndex = temp;
                }
                if (!isOnCreate) {
                    listViewKeyAdapter.notifyDataSetChanged();
                    getHttpValue(list.get(selectIndex).getDept_id(), true);
                }
            }
        }
    }

    //首頁傳過來的id
    private int homeDeptId = -1;

    private int getDeptIdToPosition(int dept_id) {
        for (int i = 0; i < list.size(); i++) {
            if (dept_id == list.get(i).getDept_id()) {
                return i;
            }
        }
        homeDeptId = dept_id;
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == RESULT_OK) {
            getHttpValue(list.get(selectIndex).getDept_id(), true);
        } else if (requestCode == 999 && resultCode == 1001) {
            top_bar_title.setText(data.getStringExtra("address"));
            sstr = top_bar_title.getText().toString();

//            getHttpValue(list.get(selectIndex).getDept_id(), true);
            Intent intent = new Intent();
            intent.setAction("gaiAddress");
            intent.putExtra("address", sstr);
            sendBroadcast(intent);
        }

    }

    /*
         * 设置点击事件
         */
    private void setOnClickListener() {
        /**
         * 左边的分类点击事件
         */

        listViewKey.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectIndex = position;
                getHttpValue(list.get(position).getDept_id(), true);
                listViewKeyAdapter.notifyDataSetChanged();

//                }
            }
        });

        /**
         * 再次刷新
         */
        tv_zcsx.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getHttpValue(list.get(selectIndex).getDept_id(), true);
            }
        });

        //右边详情页点击事件
        listViewValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startXQ(TaiTaiGouActivity.this, String.valueOf(data.get(position).getNumber()), String.valueOf(list.get(selectIndex).getDept_id()), String.valueOf(data.get(position).getId()), list.get(selectIndex).getTitle());
            }
        });
    }


    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                default:
                    break;
            }
        }
    };

    /**
     * 左边listview接口
     */
    private void getHttpClassList() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetTopGoodsCategory");
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray js = json.getJSONArray("result");
                    list.clear();
                    list.addAll(JsonHelper.parseCollection(js, ArrayList.class, CommodityClassifyData.class));
                    getHttpValue(list.get(selectIndex = getDeptIdToPosition(homeDeptId)).getDept_id(), true);

                    listViewKeyAdapter.notifyDataSetChanged();
                    customAdapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 右边listview接口
     */
    private void getHttpValue(int dept_id, final boolean isFist) {
        if (isFist) {
            pageHelp.clear();
        }
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetGoodsByCategory");
        httpRequestParams.addBodyParameter("dept_id", dept_id + "");
//        httpRequestParams.addUserId(userData);
        httpRequestParams.addBodyParameter("User_id", String.valueOf(MyApplication.shangjiaId));
        httpRequestParams.addBodyParameter("pageindex", String.valueOf(pageHelp.getPageindex()));
        httpRequestParams.addBodyParameter("Pagesize", String.valueOf(pageHelp.getPageCount()));
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    data.clear();
                    JSONObject json = new JSONObject(result);
                    JSONArray js = json.getJSONArray("result");
                    if (isFist) {
                        data.clear();
                    }
                    data.addAll(pageHelp.getValidData(JsonHelper.parseCollection(js, ArrayList.class, GoodListData.class)));


                    if (data.size() <= 0) {
                        ll_yc.setVisibility(View.VISIBLE);
                        ll_xs.setVisibility(View.GONE);
                    } else {
                        ll_yc.setVisibility(View.GONE);
                        ll_xs.setVisibility(View.VISIBLE);
                        sjID = data.get(0).getStore_id();
                        GwcDbUtil.setDataDbSelectNumber(data);
                        listViewValue.loaddingFinsh();
                    }
                    customAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.setSwipeRefreshLayout(valueSwipeRefreshLayout));
    }

    /*
     * 初始化view
     */
    private void initView() {

        tv_logo = (TextView) findViewById(R.id.tv_logo);
        tv_logo.setTextColor(getResources().getColor(R.color.black));
        logo = (ImageView) findViewById(R.id.logo);
        logo.setImageResource(R.mipmap.logo_g_1);

        // 设置顶部的标题
        top_bar_loc = (ImageView) findViewById(R.id.top_bar_loc);
        top_bar_right_iv = (ImageView) findViewById(R.id.top_bar_right_iv);
        top_bar_title = (TextView) findViewById(R.id.top_bar_title);
        top_bar_title.setText(MainActivity.str);
        ll_yc = (LinearLayout) findViewById(R.id.ll_yc);
        ll_xs = (LinearLayout) findViewById(R.id.ll_xs);
        tv_zcsx = (TextView) findViewById(R.id.tv_zcsx);
        setCurrentBotton(2);


        listViewKey = (ListView) findViewById(R.id.lv_left_key);
        listViewValue = (ListViewForAutoLoad) findViewById(R.id.lv_rigth_value);
        valueSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly_right);
        shuaxin();


        listViewValue.setOnLoaddingListener(new OnLoaddingListener() {
            @Override
            public void onLoadding() {
                getHttpValue(list.get(selectIndex).getDept_id(), false);
            }
        }, pageHelp = new PagingHelp(this));


        top_bar_right_iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaiTaiGouActivity.this, SearchActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
            }
        });

        top_bar_title.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin(true)) {
                    //实现界面跳转
                    Intent intent = new Intent(TaiTaiGouActivity.this, AddAddressActivity.class);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivityForResult(intent, 999);
                }
            }
        });


        list = new ArrayList<CommodityClassifyData>();
        listViewKeyAdapter = new ListViewKeyAdapter();
        listViewKey.setAdapter(listViewKeyAdapter);


        data = new ArrayList<GoodListData>();
        customAdapter = new ListViewValueAdapter();
        listViewValue.setAdapter(customAdapter);

    }


    /**
     * 获取广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        DbGwcData dbGwcData = new DbGwcData();

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GwcDbUtil.GWC_CHANG_CLEAR)) {
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setNumber(0);
                }
                customAdapter.notifyDataSetChanged();
            } else if (intent.getAction().equals(GwcDbUtil.GWC_CHANG_ADD)) {
                dbGwcData = (DbGwcData) intent.getSerializableExtra(GwcDbUtil.GWC_CHANG_DATA);
                for (int i = 0; i < data.size(); i++) {
                    if (dbGwcData.getId() == data.get(i).getId()) {
                        data.get(i).setNumber(dbGwcData.getSelectNumber());
                        customAdapter.notifyDataSetChanged();
                        break;
                    }

                }
            } else if (intent.getAction().equals(GwcDbUtil.GWC_CHANG_SUB)) {
                dbGwcData = (DbGwcData) intent.getSerializableExtra(GwcDbUtil.GWC_CHANG_DATA);
                for (int i = 0; i < data.size(); i++) {
                    if (dbGwcData.getId() == data.get(i).getId()) {
                        data.get(i).setNumber(dbGwcData.getSelectNumber());
                        customAdapter.notifyDataSetChanged();
                        break;
                    }

                }
            } else if (intent.getAction().equals(GwcDbUtil.DELETE_DB)) {
                dbGwcData = (DbGwcData) intent.getSerializableExtra(GwcDbUtil.GWC_CHANG_DATA);
                for (int i = 0; i < data.size(); i++) {
                    if (dbGwcData.getId() == data.get(i).getId()) {
                        data.get(i).setNumber(dbGwcData.getSelectNumber());
                        customAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    };

    BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().toString().equals("sengAddress")) {
                sstr = intent.getStringExtra("str");
                top_bar_title.setText(sstr);
            }
        }
    };

    /**
     * 下拉刷新
     */

    private void shuaxin() {
        valueSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getHttpValue(list.get(selectIndex).getDept_id(), true);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        unregisterReceiver(broadcastReceiver2);
    }

    /**
     * 左侧菜单栏
     */
    class ListViewKeyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_more_good_left_menu, null);
                viewHolder.tv_left_menu = (TextView) convertView.findViewById(R.id.tv_left_menu);
                viewHolder.tv_left_color = (TextView) convertView.findViewById(R.id.tv_left_color);
                viewHolder.ll_bj = (LinearLayout) convertView.findViewById(R.id.ll_bj);
                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            //获取数据
            viewHolder.tv_left_menu.setText(list.get(position).getTitle());
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) viewHolder.tv_left_color.getLayoutParams(); // 取控件mGrid当前的布局参数


            if (selectIndex == position) {

                linearParams.width = 20;// 当控件的高强制设成50象素
                viewHolder.tv_left_color.setLayoutParams(linearParams);
                viewHolder.tv_left_color.setBackgroundResource(R.color.main_color);
                viewHolder.ll_bj.setBackgroundResource(R.color.white);
                viewHolder.tv_left_menu.setTextColor(getResources().getColor(R.color.black));
            } else {
                linearParams.width = 0;// 当控件的高强制设成50象素
                viewHolder.tv_left_color.setLayoutParams(linearParams);
                viewHolder.tv_left_color.setBackgroundResource(R.color.gray_66);
                viewHolder.ll_bj.setBackgroundResource(R.color.gray_ee_t90);
                viewHolder.tv_left_menu.setTextColor(getResources().getColor(R.color.gray_66));
            }
            return convertView;
        }


        class ViewHolder {
            private TextView tv_left_color;
            private TextView tv_left_menu;
            private LinearLayout ll_bj;
        }

    }

    /**
     * 右侧菜单栏
     */
    class ListViewValueAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            final GoodListData itemData = (GoodListData) getItem(position);
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(TaiTaiGouActivity.this, R.layout.item_more_good_list_right_value, null);
                viewHolder.iv_picture = (ImageView) convertView.findViewById(R.id.iv_product_picture);
                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_product_name);
                viewHolder.tv_how_much = (TextView) convertView.findViewById(R.id.tv_product_how_much);
                viewHolder.tv_money = (TextView) convertView.findViewById(R.id.tv_product_money);
                viewHolder.tv_past_money = (TextView) convertView.findViewById(R.id.tv_product_past_money);
                viewHolder.number_select_view = (NumberSelectView) convertView.findViewById(R.id.number_select_view);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 获取数据
            imageManager.bind(viewHolder.iv_picture, HttpLocalUtils.getHttpFileUrl(data.get(position).getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_name.setText(data.get(position).getGname());
            viewHolder.tv_how_much.setText(data.get(position).getPknum() + (data.get(position).getUnit() == null ? "" : "/" + data.get(position).getUnit()));
            viewHolder.tv_money.setText("¥" + data.get(position).getSell_price());
            viewHolder.tv_past_money.setText("¥" + data.get(position).getOriginal_price());
            viewHolder.number_select_view.setNumber(itemData.getNumber());
            viewHolder.number_select_view.setOnItemClickListener(new NumberSelectView.OnItemClickListener() {
                @Override
                public boolean onAddClick(int num, NumberSelectView view) {
                    LogUtils.e("itemData", itemData.toString());
                    if (GwcDbUtil.addGoodAutoNumber(itemData.getDbGwcData())) {
                        itemData.setNumber(itemData.getNumber() + 1);
                        return true;
                    }
                    return false;
                }

                @Override
                public boolean onSubClick(int num, NumberSelectView view) {
                    if (GwcDbUtil.subGoodAutoNumber(itemData.getDbGwcData())) {
                        itemData.setNumber(itemData.getNumber() - 1);
//                        customAdapter.notifyDataSetChanged();
                        return true;
                    }
                    return false;
                }

            });


            return convertView;
        }

        class ViewHolder {
            private ImageView iv_picture;
            private TextView tv_name;
            private TextView tv_how_much;
            private TextView tv_money;
            private TextView tv_past_money;
            private NumberSelectView number_select_view;
        }

    }

}